package com.ac.scum.log.web.model.login.service;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

@Slf4j
@Service
public class EncodingSalt {

    @Data
    public class EncodingBean {
        private String after;
        private String context;
        private String salt;
    }

    public EncodingBean encoding(String context) {
        return encoding(context, generateSalt());
    }

    public EncodingBean encoding(String context, String salt) {
        EncodingBean encodingBean = new EncodingBean();
        // 将盐值排序
        char[] sortedSalt = sortSalt(salt);
        // 根据百分比间隔加入原文中md5
        String saltedText = addSaltToText(context, sortedSalt);
        // md5 加密
        String md5Hash = hash(saltedText);
        // 根据倒序盐加密一次
        String reversedSalt = new StringBuilder(salt).reverse().toString();
        String firstEncryption = encryptWithSalt(md5Hash, reversedSalt);
        // 根据原文盐加密一次
        String secondEncryption = encryptWithSalt(firstEncryption, salt);
        encodingBean.setAfter(secondEncryption);
        encodingBean.setSalt(salt);
        encodingBean.setContext(context);
        return encodingBean;
    }

    private String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[4];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    private char[] sortSalt(String salt) {
        char[] charArray = salt.toCharArray();
        Arrays.sort(charArray);
        return charArray;
    }

    private String addSaltToText(String text, char[] sortedSalt) {
        StringBuilder result = new StringBuilder();
        int index = 0;
        for (int i = 0; i < text.length(); i++) {
            result.append(text.charAt(i));
            if ((i + 1) % 10 == 0 && index < sortedSalt.length) {
                result.append(sortedSalt[index++]);
            }
        }
        return result.toString();
    }

    private String hash(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(text.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    private String encryptWithSalt(String text, String salt) {
        return hash(text + salt);
    }
}
